package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Configuration
public class ResourceConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

                String requestURI = request.getRequestURI();
                if (requestURI.startsWith("/index")) {
                    return true;
                }
                HttpSession session = request.getSession();
                Object login = session.getAttribute("login");
                if (login == null) {
                    response.setCharacterEncoding("UTF8");
                    response.setContentType("application/json;charset=UTF8");
                    PrintWriter writer = response.getWriter();
                    writer.write("{\"code\":" + 403 + ",\"msg\":\"" + "您还未登录！\"}");
                    return false;
                }
                return true;
            }
        });
    }
}
